package com.dzt.cloudreader.network;

import android.content.Context;
import android.content.Intent;

import com.dzt.cloudreader.model.HotMovieBean;
import com.dzt.cloudreader.mvp.MvpPresenter;
import com.dzt.cloudreader.mvp.MvpView;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by M02323 on 2017/12/28.
 */

public class TopMoviePresenter implements MvpPresenter {
	private DataManager manager;
	private CompositeSubscription mCompositeSubscription;
	private Context mContext;
	private TopMovieView movieView;
	private HotMovieBean movieBean;

	public TopMoviePresenter(Context context) {
		mContext = context;
	}

	@Override
	public void onCreate() {
		manager = DataManager.getInstance();
		mCompositeSubscription = new CompositeSubscription();
	}

	@Override
	public void onStart() {

	}

	@Override
	public void onStop() {

	}

	@Override
	public void onDestroy() {
		if (mCompositeSubscription.hasSubscriptions()) {
			mCompositeSubscription.unsubscribe();
		}
	}

	@Override
	public void attachView(MvpView view) {
		movieView = (TopMovieView) view;
	}

	@Override
	public void attachIncomingIntent(Intent intent) {

	}

	public void getMovieTop250(int start, int count) {
		mCompositeSubscription.add(manager.getMovieTop250(start, count)
				.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Observer<HotMovieBean>() {
					@Override
					public void onCompleted() {
						if (movieBean != null) {
							movieView.onSuccess(movieBean);
						}
					}

					@Override
					public void onError(Throwable e) {
						e.printStackTrace();
						movieView.onError("请求失败！！");
					}

					@Override
					public void onNext(HotMovieBean movieBean) {
						TopMoviePresenter.this.movieBean = movieBean;
					}
				}));
	}
}
